package org.example.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        //编码的时候写入类型为 int 所以长度为 4
        if (byteBuf.readableBytes() < 4) {
            return;
        }


        //标记一下当前的 ReaderIndex 位置
        byteBuf.markReaderIndex();

        //读取传递过来的消息长度。byteBuf的 readInt 方法会让他的 ReaderIndex 增加4
        int dataLength = byteBuf.readInt();


        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] data = new byte[dataLength];

        //将 byteBuf 中的数据写入到 date 数组中
        byteBuf.readBytes(data);
        Object obj = serializer.deserialize(clazz, data);
        list.add(obj);
    }
}
